<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\service\business\controllers\Access\Role\AdminRoleService;
use app\admin\validate\AdminRole;
use think\facade\View;
use think\Request;

class AdminRoleController extends BaseController
{
    /** @var AdminRoleService */
    protected $server;

    protected function initialize()
    {
        $this -> server = AdminRoleService::getInstance();
    }

    /**
     * 显示资源列表
     *
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        if($this -> request -> isAjax()){
            $params = $this -> request -> get(['key']);

            return $this -> returnData(200, '请求成功', [
                'list' => $this -> server -> resList($params, $this -> request -> get('limit', 10, 'intval')),
            ]);
        }

        //
        return View::fetch();
    }

    /**
     * 显示创建资源表单页
     *
     * @return string
     * @throws \Exception
     */
    public function create()
    {
        return View::fetch('form', [
            'data' => null,
            'rules' => json_encode($this -> server -> getRuleList())
        ]);
    }

    /**
     * 保存新建的资源
     *
     * @param Request $request
     * @return object
     */
    public function save(Request $request)
    {
        $params = $request -> param(['name', 'description', 'rules']);

        // 验证请求参数
        $this -> validate($params, AdminRole::class . '.create');

        // 处理
        $result = $this -> server -> operating($params);

        return $this -> returnData($result['code'], $result['msg'], $result['data']);
    }

    /**
     * 显示编辑资源表单页
     *
     * @param int $id
     * @return string
     * @throws \Exception
     */
    public function edit(int $id)
    {
        $result = $this -> server -> resFind($id);

        return View::fetch('form', [
            'data' => $result,
            'rules' => json_encode($this -> server -> getRuleList())
        ]);
    }

    /**
     * 保存更新的资源
     *
     * @param Request $request
     * @param int $id
     * @return object
     */
    public function update(Request $request, int $id)
    {
        $params = $request -> param(['name', 'description', 'rules']);

        $this -> validate($params, AdminRole::class . '.edit');

        $result = $this -> server -> operating($params, $id);

        return $this -> returnData($result['code'], $result['msg'], $result['data']);
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return object
     */
    public function delete(int $id)
    {
        $result = $this -> server -> del($id);

        return $this -> returnData($result['code'], $result['msg'], $result['data']);
    }
}
